package com.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Xml_DB {

	private static ObjectMapper mapper = new ObjectMapper();

	/**

	 * 获取表的全部数据

	 * 

	 * @param path

	 * @param tablename

	 * @return

	 * @throws DocumentException 

	 * @throws IOException 

	 * @throws JsonMappingException 

	 * @throws JsonParseException 

	 * @throws Exception

	 */
	public List<Map<String,Object>> loadTableDatas(String path, String tablename) throws DocumentException, IOException {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(path);
		Element root = document.getRootElement();

		List<Map<String,Object>> l = new ArrayList<Map<String,Object>>();
		List<Element> list = root.elements();
		for (Element x : list) {
			if (x.attributeValue("name").equals(tablename)) {
				List<Element> al = x.elements();
				for (Element s : al) {
					String data = s.getText();
					if (data == null) {
						break;
					}
					Map mp = mapper.readValue(data, Map.class);
					l.add(mp);
				}
			}
		}
		return l;
	}

	/**

	 * 表插入数据

	 * 

	 * @param path

	 * @param tablename

	 * @param po

	 * @return

	 * @throws JDOMException

	 * @throws IOException

	 * @throws DocumentException 

	 */
	public boolean addData(String path, String tablename, Object po)
			throws IOException, DocumentException {
		boolean flag = false;
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(path);
		Element root = document.getRootElement();

		List<Element> list = root.elements();
		for (Element x : list) {
			if (x.attributeValue("name").equals(tablename)) {
				Map<String,Object> base = new HashMap<String,Object>();
				String json = mapper.writeValueAsString(po);
				Map<String,Object> mp = mapper.readValue(json, Map.class);
				base.putAll(mp);
				base.put("_uuid", UUID.randomUUID().toString());
				Element data = x.addElement("data");
				data.setText(mapper.writeValueAsString(base));
			}
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(path),format);  	      
        xmlWriter.write(document);  
        xmlWriter.close();  
		flag = true;
		System.out.println("----------insert --- data --- success----------------------");
		return flag;
	}

	/**

	 * 表修改数据

	 * 

	 * @param path

	 * @param tablename

	 * @param po

	 * @throws JDOMException

	 * @throws IOException

	 * @throws DocumentException 

	 */
	public void updateData(String path, String tablename, Object po)
			throws IOException, DocumentException {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(path);
		Element root = document.getRootElement();

		List<Element> list = root.elements();
		for (Element x : list) {
			if (x.attributeValue("name").equals(tablename)) {
				List<Element> al = x.elements();
				for (Element s : al) {
					// 如果定位Data[通过UUID唯一标示]

					Map<String,Object> mp = mapper.readValue(s.getText(), Map.class);
					Map<String,Object> newmp = mapper.readValue(mapper.writeValueAsString(po), Map.class);
					if (mp.get("_uuid").equals(newmp.get("_uuid"))) {
						mp.putAll(newmp);
						x.remove(s);
						Element data = x.addElement("data");
						data.setText(mapper.writeValueAsString(mp));
						break;
					}
				}
			}
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(path),format);  	      
        xmlWriter.write(document);  
        xmlWriter.close();  
		System.out.println("----------update --- data --- success----------------------");
	}

	/**

	 * 表删除数据

	 * 

	 * @param path

	 * @param tablename

	 * @param po

	 * @throws JDOMException

	 * @throws IOException

	 * @throws DocumentException 

	 */
	public void deleteData(String path, String tablename, Object po)
			throws IOException, DocumentException {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(path);
		Element root = document.getRootElement();
		List<Element> list = root.elements();
		for (Element x : list) {
			List<Element> al = x.elements();
			if (x.attributeValue("name").equals(tablename)) {
				for (Element s : al) {
					// 如果定位Data[通过UUID唯一标示]					

					Map<String,Object> mp = mapper.readValue(s.getText(), Map.class);
					Map<String,Object> newmp = mapper.readValue(mapper.writeValueAsString(po), Map.class);
					if (mp.get("_uuid").equals(newmp.get("_uuid"))) {
						x.remove(s);
						break;
					}
				}
			}
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(path),format);  	      
        xmlWriter.write(document);  
        xmlWriter.close();  
		System.out.println("----------delete --- data --- success----------------------");
	}

	/**

	 * 创建数据库

	 * 

	 * @param path

	 * @throws Exception

	 */
	public void createDataBase(String path) throws Exception {

		Document document = DocumentHelper.createDocument();
		Element root = document.addElement("database");
		
		Element test_node = root.addElement("table");
		test_node.addAttribute("name", "test");
		
		Element index_node = root.addElement("table");
		index_node.addAttribute("name", "system.indexs");
		
		Element user_node = root.addElement("table");
		user_node.addAttribute("name", "system.users");

		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter xmlWriter = new XMLWriter(new FileOutputStream(path),format);  	      
        xmlWriter.write(document);  
        xmlWriter.close();  
        System.out.println("----------create---database---success-------------------");
	}
}
